package com.fla.aiba.api;

import com.fla.aiba.comm.config.Config;
import com.fla.aiba.comm.config.OnLineLiveCache;
import com.fla.aiba.dto.LiveDto;
import com.fla.aiba.entity.live.*;
import com.fla.aiba.repository.*;
import com.fla.aiba.repository.live.LiveGiftDetailRepository;
import com.fla.aiba.service.LiveService;
import com.fla.aiba.service.UserService;
import com.fla.live.im.RoomManage;
import com.fla.aiba.util.HttpUtil;
import com.fla.aiba.util.UploadUtil;
import com.jiai.core.tools.RestResultGenerator;
import com.jiai.exception.ServiceException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;


@SuppressWarnings("ALL")
@RestController
@RequestMapping("/api/v1/live")
public class LiveAPIContller {
	
	@Autowired
	private LiveRepository liveRepository;
	@Autowired
	private LiveFollowRepository followRepository;

	@Autowired
	private Config config;
	@Autowired
	private LiveRoomRepository liveRoomRepository;
	@Autowired
	private LiveApplyRepository liveApplyRepository;
	@PersistenceUnit
	private EntityManagerFactory emf;

	@Autowired
	private LiveService liveService;


	private LiveGiftDetailRepository liveGiftDetailRepository;
	@Autowired
	private UserService userService;
	/**
	 * 加载当前在直正在直播的主播
	 * @param liveSearch
	 * @return
	 */
	@RequestMapping(value="/load",method= RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
	public Object loadNewsLive()throws ServiceException {
		try {
			return RestResultGenerator.genSuccessResult(OnLineLiveCache.getAll());
		} catch (Exception e) {
			throw new ServiceException("获取最新的主播列表失败", e.getMessage());
		}
	}




	 /**
	 * 关注主播
	 * @param user
	 * @param liveId
	 * @return
	 */
	@RequestMapping(value="/follow/{followTo}",method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
	public Object follow( @PathVariable("followTo") String followTo)throws ServiceException{
		try{
			LiveFollow follow=new LiveFollow();
			follow.setFollowUseId(followTo);
			follow.setUserId(HttpUtil.getUserId());
			follow.setFollowTime(new Date());
			followRepository.save(follow);
			return RestResultGenerator.genSuccessResult();
		}catch (Exception e){
			throw new ServiceException("关注主播失败",e.getMessage());
		}
	}

	/**
	 * 加载主播关注者
	 * @param userId
	 * @return
	 * @throws ServiceException
	 */
	@RequestMapping(value="/loadFolowUser/{userId}",method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
	public Object loadFollowUser(@PathVariable("userId") String userId)throws ServiceException{
			return RestResultGenerator.genSuccessResult(liveService.findFollowMy(userId));
	}


	/**
	 * 结束直播并反馈本次直播的祥情
	 * @param liveId
	 * @return
	 * @throws ServiceException
	 */
	@RequestMapping(value="/stopLive/{liveId}",method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
	public  Object stopLive(@PathVariable("liveId") Integer liveId)throws ServiceException{
		try {

			LiveRoom room= RoomManage.getInstance().getRoom(liveId);
			LiveDto view= OnLineLiveCache.getByRoomId(room.getId());
			room.setEndTime(new Date());
			room.setStatus(2);
			room=emf.createEntityManager().merge(room);
			OnLineLiveCache.remove(room.getId());
			return RestResultGenerator.genSuccessResult(room);
		}catch (Exception e){
			throw  new ServiceException("stop live serror",e.getMessage());
		}
	}

	/**
	 * 开始直播并返回分配的房间信息
	 * @param liveId
	 * @param liveRoom
	 * @param request
	 * @return
	 * @throws ServiceException
	 */
	@RequestMapping(value="/startLive/{userId}",method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
	public Object startLive(@PathVariable("userId") String userId, LiveRoom room, HttpServletRequest request)throws ServiceException{
		try {
			LiveDto view=liveService.findByUserId(userId);
			if(view==null)
				return RestResultGenerator.genErrorResult("重播不存在");
			Live live=new Live();
			live.setLiveId(view.getLiveId());
			room.setLive(live);
			room.setStartTime(new Date());
			room.setLiveUrl(config.getLiveUrl()+"/"+view.getLiveId());
			room=liveRoomRepository.save(room);
			view.setLiveUrl(room.getLiveUrl());
			view.setNotice(live.getNotice());
			view.setOnlineNumber(1);
			view.setRent(room.getRent());
			view.setTitle(live.getTitle());
			OnLineLiveCache.addLive(room.getId(),view);
			//RoomManage.getInstance().addRoom(room);
			return  RestResultGenerator.genSuccessResult(room);
		}catch (Exception e){
			throw  new ServiceException("直播失败",e.getMessage());
		}
	}

	/**
	 * 申请主播
	 * @param Live
	 * @return
	 */
	@RequestMapping(value="/applyLive",method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
	public Object applyLive(LiveApply apply, @RequestParam("file")MultipartFile file)throws ServiceException{
		try {
			String filePath= UploadUtil.copyFile(file, "live");
			apply.setUserId(HttpUtil.getUserId());
			apply.setApplyTime(new Date());
			liveApplyRepository.save(apply);
			Live live=new Live();
			live.setTitle("");
			live.setUser(HttpUtil.getUser());
			liveRepository.save(live);
			return RestResultGenerator.genSuccessResult(live);
		} catch (Exception e) {
			throw new ServiceException("申请失败",e.getMessage());
		}

	}

	/**
	 * 赠送礼物给主播
	 * @param liveGiftDetail
	 * @return
	 * @throws ServiceException
	 */
	@RequestMapping(value = "sendGift",method = RequestMethod.POST)
	public Object sendGift(LiveGiftDetail liveGiftDetail)throws  ServiceException{
		 try {
			 liveGiftDetail.setFrom(HttpUtil.getUserId());
			 liveGiftDetail.setSendTime(new Date());
			 liveGiftDetailRepository.save(liveGiftDetail);
			 return RestResultGenerator.genSuccessResult("赠送成功");
			}catch (Exception e){
		 	throw  new ServiceException(e.getMessage());
		 }
	}
	
}
